<template>
    <Drawer v-model="showCreate" :mask-closable="false" :title="edit ? '录入线索' : '编辑线索'" width="900">
        <Form ref="create" :model="createData" label-position="top">
            <Row :gutter="24">
                <Col span="6">
                    <FormItem label="姓名"><Input v-model="createData.user_name" placeholder="请输入姓名" /></FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="手机号">
                        <Input v-model="createData.mobile" @on-blur="repeatfun(createData.mobile,1)" @on-keyup="createData.mobile=createData.mobile.replace(/\s+|[\r\n]/g,'')" placeholder="请输入手机号"></Input>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="微信号">
                        <Input v-model="createData.wechat_num" @on-blur="repeatfun(createData.wechat_num,2)" placeholder="请输入微信号" @on-keyup="createData.wechat_num=createData.wechat_num.replace(/\s+|[\r\n]/g,'')" ></Input>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="抖音号">
                        <Input v-model="createData.dy_num" @on-blur="repeatfun(createData.dy_num,3)" @on-keyup="createData.dy_num=createData.dy_num.replace(/\s+|[\r\n]/g,'')" placeholder="请输入抖音号"></Input>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="部位">
                        <TreeSelect v-model="createData.body_parts_ids" :data="postList" clearable multiple />
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="年龄">
                        <InputNumber :max="100" :min="1" v-model="createData.age"></InputNumber>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="性别">
                        <RadioGroup v-model="createData.gender">
                            <Radio :label="1">男</Radio>
                            <Radio :label="2">女</Radio>
                            <Radio :label="0">未知</Radio>
                        </RadioGroup>
                    </FormItem>
                </Col>
                <Col span="6">
                    <FormItem label="渠道">
                        <TreeSelect v-width="150" v-model="createData.channel_id" :data="channelList" filterable
                            clearable placeholder="来源渠道" />
                    </FormItem>
                </Col>
                <Col span="24">
                    <FormItem label="渠道备注">
                        <Input v-model="createData.source_remark" placeholder="请输入"></Input>
                    </FormItem>
                </Col>
                <Col span="24">
                    <FormItem label="备注">
                        <Input v-model="createData.customer_remark" placeholder="请输入"></Input>
                    </FormItem>
                </Col>
                <Col span="24" class="ivu-mb">
                <template>
                    <div class="demo-upload-list" v-for="(item, index) in uploadList" :key="index">
                        <template>
                            <img :src="item.url"/>
                            <div class="demo-upload-list-cover">
                                <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                                <Icon type="ios-trash-outline" @click.native="removeUpload(item.urls)"></Icon>
                            </div>
                        </template>
                    </div>
                    <Upload ref="upload" :on-success="successUpload" :default-file-list="defaultList"
                        :format="['jpg', 'jpeg', 'png']" :show-upload-list="false" multiple type="drag"
                        :data="datas" name="files" :action="`${url}/v1/upload/images`"
                        style="display: inline-block; width: 58px;">
                        <div style="
                                    width: 58px;
                                    height: 58px;
                                    line-height: 58px;
                                ">
                            <Icon type="ios-camera" size="20"></Icon>
                        </div>
                    </Upload>
                    <span style="padding-left: 10px;">请点击上传或拖入聊天图片上传</span>
                    <Modal title="聊天记录" footer-hide v-model="visible" width="480">
                        <img :src="imgName" v-if="visible" style="width: 100%;" />
                    </Modal>
                </template>
                </Col>
            </Row>
            <div class="demo-drawer-footer">
                <Button style="margin-right: 8px;" @click="handleDrawerCancels">取消</Button>
                <Button type="primary" :loading="remarksloading" @click="handleCreate">保存</Button>
            </div>
        </Form>
        <div class="ivu-pt-16" v-if="!edit">
            <Timeline class="ivu-mt-16">
                <TimelineItem v-for="(item, index) in clue_contact_results_list" :key="index">
                    <p class="time">{{ item.created_at }}</p>
                    <p class="content">{{ item.remark }}</p>
                </TimelineItem>
            </Timeline>
        </div>
        <copytable ref="copytable" @submitfun="add_or_edit_patient(edit,createDataing)" @cancelfun="remarksloading = false"/>
    </Drawer>
</template>

<script>
import {
    clueuserinfo,
    clueusercreate,
    clueuserupdate,
    patientindexsearchcity,
    clueusercontact,
    checkPhone_Wx,
    clueusersearchrepeat,
    repeatData,
    clueuserexport,
    patientindexsearchmobile,
    clueuserrepeatuser,
    clueusersearchmobile,
} from "@api/hqapi";
import copytable from "@/components/copytables";
export default {
    name: 'createdrawer',
    components: { copytable },
    data() {
        return {
            edit: false,
            showCreate: false,
            createData: {
                id: undefined,
                user_name: "",
                mobile: "",
                wechat_num: "",
                qq_num: "",
                dy_num: '',
                age: null,
                gender: "",
                channel_id: "",
                customer_remark: "",
                source_remark: "",
                body_parts_ids: [],
                upload_talk_img: [],
            },
            postList: [],
            channelList: [],
            clueList: [],
            operationMember: [],
            operationMembers: [],
            uploadList: [],
            defaultList: [],
            datas: {},
            visible:false,
            remarksloading: false,
            clue_contact_results_list: [],
            url: '',
            imgName: '',
        };
    },

    mounted() {
        
    },

    methods: {
        initial(id) {
            this.createData.id = id
            this.url = this.$Setting.apiBaseURL;
            if (id) this.edit = false;
            else this.edit = true;
            this.clueuserinfofun(id);
            this.showCreate = true;
        },
        askData() {
            this.$emit('askData');
        },
        clueuserinfofun(id) {
            return new Promise((resolve, reject) => {
                this.channelList = [];
                clueuserinfo({ id, type: 2 }).then((res) => {
                    if (res.contact.length && res.contact[res.contact.length - 1].status_name === '转客户') {
                        this.contactClue = false
                        this.$Modal.warning({
                            title: '提示消息',
                            content: '该条线索已被转客户，请处理其它线索',
                            onOk: () => {
                                this.askData()
                            }
                        });
                    }
                    this.postList = res.body_parts_list;
                    res.source_channel.forEach((item) => {
                        if (+item.source_type === 0) this.channelList.push(item);
                    });
                    this.department = res.department
                    if (this.taloading && res.department.length) {
                        this.taloading = false
                    }
                    this.clueList = res.clue_status;
                    this.operationMembers = res.operation_member;
                    this.operationMember = res.operation_member;
                    this.contact_member = res.contact_member;
                    this.clue_contact_results_list =
                        res.info.clue_contact_results_list;
                    this.createData = {
                        id: id,
                        user_name: res.info.user_name,
                        age: res.info.age === 0 ? 0: res.info.age?res.info.age : null,
                        gender_str: res.info.gender_str,
                        source_remark: res.info.source_remark,
                        mobile: res.info.mobile,
                        wechat_num: res.info.wechat_num,
                        qq_num: res.info.qq_num,
                        dy_num: res.info.dy_num,
                        gender: res.info.gender,
                        channel_id: res.info.channel_id + "",
                        customer_remark: res.info.customer_remark,
                        body_parts_ids: res.info.body_parts_id_arr,
                        upload_talk_img: JSON.stringify(res.info.upload_talk_img),
                    },
                    this.logs(this.createData.age)
                    this.defaultList = [];
                    this.uploadList = [];
                    for (let item of res.info.upload_talk_img) {
                        this.defaultList.push({
                            name: res.info.images_host,
                            url: item,
                        });
                        this.uploadList.push({
                            url: `${res.info.images_host}${item}`,
                            urls: item,
                        });
                    }
                    resolve()
                });
            })
        },
        // 上传文件
        successUpload(response, file, fileList) {
            let list = [];
            let lists = [];
            for (let item of fileList) {
                if (item.response) {
                    list.push(item.response.data.path[0]);
                    lists.push({
                        url: `${item.response.data.host}${item.response.data.path[0]}`,
                        urls: item.response.data.path[0],
                    });
                }
                if (item.url) {
                    list.push(item.url);
                    lists.push({
                        url: `${item.name}${item.url}`,
                        urls: item.url,
                    });
                }
            }
            //  数组去重
            this.createData.upload_talk_img = JSON.stringify(
                Array.from(new Set(list))
            );
            this.uploadList = Array.from(new Set(lists));
        },
        handleDrawerCancels() {
            this.$refs.create.resetFields();
            this.showCreate = false;
        },
        // 新增或编辑提交
        handleCreate() {
            this.remarksloading = true;
            this.createDataing = { ...this.createData };
            this.createDataing.body_parts_ids = this.createDataing.body_parts_ids.join(",");
            if (this.createData.mobile || this.createData.wechat_num || this.createData.dy_num) {
                let params = {
                    mobile: this.createData.mobile,
                    type: 1,
                    wechat_num: this.createData.wechat_num,
                    dy_num: this.createData.dy_num,
                    data_type: 1,
                    id: this.createData.id
                }
                this.$refs.copytable.initial(params)
            } else {
                this.add_or_edit_patient(this.edit, this.createDataing);
            }
        },
        add_or_edit_patient(type, params) {
            let pid = "";
            for (let items of this.channelList) {
                if (+params.channel_id === +items.id) {
                    pid = items.pid;
                } else {
                    for (let item of items.children) {
                        if (+params.channel_id === +item.id) {
                            pid = item.pid;
                        }
                    }
                }
            }
            if (type) {
                clueusercreate({ ...params, pid })
                    .then(() => {
                        this.remarksloading = false;
                        this.askData();
                        this.showCreate = false;
                    })
                    .catch(() => {
                        this.remarksloading = false;
                    });
            } else {
                clueuserupdate({ ...params, pid })
                    .then(() => {
                        this.askData();
                        this.remarksloading = false;
                        this.showCreate = false;
                    })
                    .catch(() => {
                        this.remarksloading = false;
                    });
            }
        },
        handleView(url) {
            this.imgName = url;
            this.visible = true;
        },
        removeUpload(urls) {
            const fileList = this.$refs.upload.fileList;
            for (let index in fileList) {
                if (fileList[index].response) {
                    if (urls === fileList[index].response.data.path[0]) {
                        this.$refs.upload.fileList.splice(index, 1);
                    }
                }
                if (fileList[index].url) {
                    if (urls === fileList[index].url) {
                        this.$refs.upload.fileList.splice(index, 1);
                    }
                }
            }
            let list = [];
            let lists = [];
            for (let item of fileList) {
                if (item.response) {
                    list.push(item.response.data.path[0]);
                    lists.push({
                        url: `${item.response.data.host}${item.response.data.path[0]}`,
                        urls: item.response.data.path[0],
                    });
                }
                if (item.url) {
                    list.push(item.url);
                    lists.push({
                        url: `${item.name}${item.url}`,
                        urls: item.url,
                    });
                }
            }
            //  数组去重
            this.createData.upload_talk_img = JSON.stringify(
                Array.from(new Set(list))
            );
            this.uploadList = Array.from(new Set(lists));
        },
        repeatfun(data, num) {
            let config = {
                data_type: 1,
                type: 0,
                id: this.createData.id ? 0 : this.createData.id,
                mobile: '',
                wechat_num: '',
                dy_num: ''
            }
            if (num === 1) config.mobile = data
            else if (num === 2) config.wechat_num = data
            else if (num === 3) config.dy_num = data
            clueusersearchrepeat(config).then((res) => {
                if (res) {
                    this.$Message.warning({
                        duration: 2.5,
                        content: num === 1 ? "该手机号码已存在" : num === 2 ? "该微信号已存在": '该抖音号已存在',
                    });
                }
            });
        },
    },
};
</script>
<style scoped>
    .repeatColor {
        color: red;
    }

    .person {
        color: #999;
    }

    .demo-upload-list {
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
        margin-right: 4px;
    }

    .demo-upload-list img {
        width: 60px;
        height: 60px;
        object-fit: contain;
    }

    .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, 0.6);
    }

    .demo-upload-list:hover .demo-upload-list-cover {
        display: block;
    }

    .demo-upload-list-cover i {
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }

    .content {
        white-space: pre-wrap;
    }
</style>